package com.heking.securityapp.pages;

import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import com.heking.security.LogUtils;
import com.heking.security.ssl.ZSSLHelper;
import com.heking.security.webview.BaseWebViewClient;
import com.heking.security.webview.WebViewUtils;
import com.heking.securityapp.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import androidx.appcompat.app.AppCompatActivity;

public class SslCheckActivity extends AppCompatActivity {
    private static final String TAG = ">>>SslCheckActivity";
    private static final String BAIDU = "https://www.baidu.com/";
    private static final String CSDN = "https://www.csdn.net/";
    private static final String TAOBAO = "https://www.taobao.com";
    private static final String GUANGDONG = "https://kit.vgmcc.com:8001/Content/systemsaferules.html";

    private WebView mWebView;
    private Button mBtn1;
    private Button mBtn2;
    private Button mBtn3;
    private Button mBtn4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ssl_check);

        findViews();
        WebSettings webSettings = WebViewUtils.settingsConfig(mWebView);
        webSettings.setDefaultFontSize(getResources().getDimensionPixelSize(R.dimen.s_14sp));
        mWebView.setWebViewClient(new BaseWebViewClient() {
            @Override
            public void onLoading() {

            }

            @Override
            public void onLoadingFinish() {

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }
        });
//        initSsl1();
        initSsl2();

        mBtn1.setOnClickListener(v -> {
//            mWebView.loadUrl(BAIDU);
            getMethod(BAIDU);

        });
        mBtn2.setOnClickListener(v -> {
//            mWebView.loadUrl(CSDN);
            getMethod(CSDN);
        });
        mBtn3.setOnClickListener(v -> {
//            mWebView.loadUrl(TAOBAO);
            getMethod(TAOBAO);
        });
        mBtn4.setOnClickListener(v -> {
//            mWebView.loadUrl(GUANGDONG);
            getMethod(GUANGDONG);
        });
    }

    private void findViews() {
        mWebView = findViewById(R.id.webView);
        mBtn1 = findViewById(R.id.btn1);
        mBtn2 = findViewById(R.id.btn2);
        mBtn3 = findViewById(R.id.btn3);
        mBtn4 = findViewById(R.id.btn4);
    }

    private void initSsl1() {
        List<String> certPathList = Arrays.asList(
//                "certificates/baidu.cer",
//                            "certificates/csdn.cer",
                "certificates/taobao.cer"
        );
        String clientPath = "certificates/client.p12";
//        clientPath=null;
        String pwd = "hk123*456";
        ZSSLHelper zsslHelper = ZSSLHelper.getInstance(this, certPathList, clientPath, pwd);
        SSLContext sslContext = zsslHelper.getSslContext();
        if (sslContext != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } else {
            LogUtils.e(TAG, "sslContext is null");
        }

    }

    private void initSsl2(){
        File folder=new File(getFilesDir(),"cers");
        String clientPath =null;
        List<String> paths=new ArrayList<>();
        if(folder.exists()){
            File[] files = folder.listFiles();
            if(files!=null && files.length>0){
                for (File item : files) {
                    String absolutePath = item.getAbsolutePath();
                    if(absolutePath.endsWith(".cer")|| absolutePath.endsWith(".crt")){
                        LogUtils.d(TAG, "absolutePath:"+absolutePath);
                        paths.add(absolutePath);
                    }else if(absolutePath.endsWith("client.p12")){
                        clientPath=absolutePath;
                    }
                }
            }
        }
        String pwd = "hk123*456";
        ZSSLHelper zsslHelper = ZSSLHelper.getInstance(paths, clientPath, pwd);
        SSLContext sslContext = zsslHelper.getSslContext();
        if (sslContext != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } else {
            LogUtils.e(TAG, "sslContext is null");
        }
    }


    private void getMethod(String urlString) {
        new Thread(() -> {
            try {
                URL url = new URL(urlString);
                HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
//                copyInputStreamToOutputStream(in, System.out);
                loadToWeb(in);
            } catch (Exception e) {
                e.printStackTrace();
                loadData(urlString+" : "+e.getMessage());
            }
        }).start();
    }

    private void loadToWeb(InputStream in) {
        ByteArrayOutputStream bos = null;
        boolean success = false;
        try {
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int c = 0;
            while ((c = in.read(buffer)) != -1) {
                bos.write(buffer, 0, c);
            }
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
            loadData(e.getMessage());
        } finally {
            if (success) {
                byte[] bytes = bos.toByteArray();
                if (bytes != null && bytes.length > 0) {
                    loadData(new String(bytes, 0, bytes.length, StandardCharsets.UTF_8));
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

    }

    private void loadData(String data) {
        runOnUiThread(() -> mWebView.loadData(data, WebViewUtils.MIMETYPE_TEXT_HTML, null));
    }

    private void copyInputStreamToOutputStream(InputStream in, PrintStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int c = 0;
        while ((c = in.read(buffer)) != -1) {
            out.write(buffer, 0, c);
        }

    }

    @Override
    public void onBackPressed() {
        WebViewUtils.onBackPressed(mWebView, this);
    }


}